package com.twan.kotlinbase.pop

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import butterknife.ButterKnife
import butterknife.OnClick
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.lxj.xpopup.core.BottomPopupView
import com.twan.kotlinbase.BuildConfig
import com.twan.kotlinbase.R
import com.twan.kotlinbase.app.Need
import com.twan.kotlinbase.bean.*
import com.twan.kotlinbase.network.RxHttpScope
import com.twan.kotlinbase.ui.CalendarActivity
import com.twan.kotlinbase.ui.CommitOrderActivity
import com.twan.kotlinbase.util.DictUtils
import com.twan.kotlinbase.util.GlideUtils
import com.twan.kotlinbase.util.RxPermissionsUtil
import com.twan.kotlinbase.util.toSafeFloat
import com.twan.kotlinbase.widgets.router.Router
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import kotlinx.android.synthetic.main.pop_my_bottom_demo.view.*
import kotlinx.android.synthetic.main.pop_my_bottom_guige.view.*
import org.greenrobot.eventbus.EventBus
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

/**
 * 调用方式: XPopup.Builder(this).asCustom(AddPicPopup(this)).show()
 */
class GuigeVideoMakePopup(context: Activity, var need: Need, var serviceBean: ServiceBean, var serviceDetail: ServiceDetail) : BottomPopupView(context) {
    private var mContext = context
    lateinit var mLastDone:Dict
    var mServiceGuige = listOf<ChidlGuige>()
    var mZuheList = listOf<GuigeZuhe>()
    lateinit var mTakeType:ChidlGuige
    lateinit var mTime:ChidlGuige
    lateinit var mNeddActor:ChidlGuige
    lateinit var mZuhe:GuigeZuhe //最终选择的组合
    override fun getImplLayoutId(): Int {
        return R.layout.pop_my_bottom_guige
    }

    override fun onCreate() {
        super.onCreate()
        ButterKnife.bind(this)
        ll_video_make.visibility= View.VISIBLE
        tv_amt.text="¥${serviceDetail.baseItemDTO.price}"
        tv_name.text="¥${serviceDetail.baseItemDTO.title}"
        GlideUtils.load(mContext,iv_avater,serviceDetail.baseItemDTO.imageUrl)
        getSkulist()
        getGuigeByServiceId()
        initRadioButton(rg_day)
    }

    fun getSkulist(){
        RxHttpScope().launch {
            var req=RxHttp.get("serviceSku/findAllByServiceId").add("serviceId",serviceBean.id).toResponse<List<GuigeZuhe>>().await()
            mZuheList=req
        }
    }
    fun getGuigeByServiceId(){
        RxHttpScope().launch {
            var req=RxHttp.get("attrValue/findAllByServiceId").add("serviceId",serviceBean.id).toResponse<List<ChidlGuige>>().await()
            mServiceGuige=req

            initRadioButton(rg_make_type,"1")//拍摄方式
            initRadioButton(rg_time,"2")//时长
            initRadioButton(rg_isneed_actor,"3")//是否需要演员
        }
    }

    fun initRadioButton(radioGroup: RadioGroup,attrKeyId:String){
        var datas = mServiceGuige.filter {
            it.attrKeyId == attrKeyId
        }
        radioGroup.weightSum=datas!!.size.toFloat()
        datas.forEachIndexed { index, dict ->
            var rbView = mContext.layoutInflater.inflate(R.layout.radio_button,radioGroup,false) as RadioButton
            rbView.text=dict.attrLabel
            rbView.id=index
            rbView.setOnCheckedChangeListener { buttonView, isChecked ->
                if (isChecked) {
                    when (attrKeyId) {
                        "1" -> {
                            mTakeType = dict
                        }
                        "2" -> {
                            mTime=dict
                        }
                        else -> {
                            mNeddActor=dict
                        }
                    }
                    updateTotalPrice()
                }
            }
            if (index==0) rbView.isChecked=true
            radioGroup.addView(rbView)
        }
    }

    //最晚完成时间, 不影响价格
    fun initRadioButton(radioGroup: RadioGroup){
        var times =DictUtils.getDictCache(DictUtils.short_video_promote)
        radioGroup.weightSum=times!!.size.toFloat()
        times.forEachIndexed { index, dict ->
            var rbView = mContext.layoutInflater.inflate(R.layout.radio_button,radioGroup,false) as RadioButton
            rbView.text=dict.label
            rbView.id=dict.id
            rbView.setOnCheckedChangeListener { buttonView, isChecked ->
                if (isChecked) {
                    mLastDone=dict
                }
            }
            if (index==0) rbView.isChecked=true
            radioGroup.addView(rbView)
        }
    }

    fun updateTotalPrice(){
        if (mZuheList.isEmpty()) {
            return
        }
        if (::mTakeType.isInitialized && ::mTime.isInitialized && ::mNeddActor.isInitialized) {
            var num = edt_num.text.toString().toInt()
            var zuhe = mZuheList.filter {
                it.attrSymbolLabel.contains(mTakeType.attrLabel + ",")
            }.filter {
                it.attrSymbolLabel.contains(mTime.attrLabel + ",")
            }.filter {
                it.attrSymbolLabel.contains(mNeddActor.attrLabel)
            }

            mZuhe = zuhe[0]
            var zukePrice = zuhe[0].price
            var totalPrice = zukePrice.toFloat().times(num)
            tv_amt.text = "¥${totalPrice}"
            serviceBean.totalAmount=totalPrice.toString()
        }
    }

    @OnClick(R.id.iv_close)
    fun close(){
        this.dismiss()
    }

    @OnClick(R.id.tv_minus)
    fun minus(){
        if (edt_num.text.toString() =="1") return
        edt_num.text = "${edt_num.text.toString().toInt()-1}"
        updateTotalPrice()
    }

    @OnClick(R.id.tv_add)
    fun add(){
        edt_num.text = "${edt_num.text.toString().toInt()+1}"
        updateTotalPrice()
    }

    @OnClick(R.id.btn_ok)
    fun confirm(){
        if (!::mZuhe.isInitialized){
            ToastUtils.showShort("该服务缺少规格")
            return
        }
        updateTotalPrice()
        var shortVideoMakeFormat= ShortVideoMakeFormat(edt_num.text.toString(),mLastDone.id,mZuhe.id)
        Router.newIntent(mContext)
                .putSerializable("need",need)
                .putSerializable("shortVideoMakeFormat",shortVideoMakeFormat)
                .putSerializable("serviceBean",serviceBean)
                .to(CommitOrderActivity::class.java).launch()
        this.dismiss()
    }

}